package com.sinbad.interview.solution.question02.case02;

import java.io.*;

/**
 * 1. 预处理阶段：分桶
 * java
 *
 * @author sinbad.cheng
 * @since 2025-04-14 17:50
 */
public class BucketSplitter {

    public static void splitFile(String inputPath, String bucketDir, int bucketCount) throws IOException {
        // 创建分桶目录
        File dir = new File(bucketDir);
        if (!dir.exists()) {
            dir.mkdirs(); // 确保目标目录存在
        }

        BufferedReader reader = new BufferedReader(new FileReader(inputPath));
        BufferedWriter[] writers = new BufferedWriter[bucketCount];
        for (int i = 0; i < bucketCount; i++) {
            writers[i] = new BufferedWriter(new FileWriter(bucketDir + "/bucket_" + i + ".txt"));
        }

        String line;
        while ((line = reader.readLine()) != null) {
            int num = Integer.parseInt(line.trim());
            int bucket = Math.abs(Integer.hashCode(num)) % bucketCount;
            writers[bucket].write(num + "\n");
        }

        for (BufferedWriter writer : writers) writer.close();
        reader.close();
    }
}
